#! /usr/bin/perl -w
#---------------------------------------------------------------------------------
#  make_holiday.pl is part of the BART dashboard widget.  (c) 2005 Bret Victor
#  This software is licensed under the terms of the open source MIT license.
#---------------------------------------------------------------------------------
#
#  perl make_holiday.pl > Holiday.js
#
#  Downloads the holiday service levels from bart.gov and generates a JavaScript
#  holiday list on stdout.  This becomes the Holiday.js file.
# 

use strict;

#-----------------------------------------------------------------
#  Main code

print STDERR "Generating holidays...\n";

print getHeader();
my $url = makeBartUrl();
my $html = getFromUrl($url);
print parseHtml($html);
print getFooter();
exit();


#-----------------------------------------------------------------
#  Main subroutines

sub makeBartUrl {
    return "http://www.bart.gov/guide/holidays.aspx"
}

sub getFromUrl {
    my ($url) = @_;
    # I'd rather use LWP, but I can't get CPAN to work.
    # return `wget --quiet -O - $url`;
    return `curl --silent '$url'`;
}

#-----------------------------------------------------------------
#  Bart HTML input parsing

sub parseHtml {
    my ($html) = @_;
    my $out = "\n    servicelevel = {}\n";

    # Jump ahead to avoid matching some earlier tables.
    $html =~ m{<p><strong>Service</strong></p>}g;
    while ($html =~ m{<!-- (.*?) --><p></td><td><p>(.*?)<p></td></tr>}gs) {
        my ($date, $service) = ($1, $2);
        $service = lc($service);
        $out .= "    servicelevel['$date'] = '$service'\n";
    }
    
    return $out;
}

#-----------------------------------------------------------------
#  JavaScript output generation

sub getHeader {
    my $now = localtime;
    return <<_EOT_;
//-----------------------------------------------------------------------------
//  Holiday.js is part of the BART dashboard widget.  (c) 2005 Bret Victor
//  This software is licensed under the terms of the open source MIT license.
//-----------------------------------------------------------------------------
//
//  Service Levels -- http://www.bart.gov/guide/holidays.aspx
//
//  Automatically generated by make_holiday.pl on $now.
//

function Holiday () {
_EOT_
}

sub getFooter {
    return <<_EOT_;
    
    Holiday.getServiceLevel = function(date) {
        var date_string = date.toMMDDYYYYString()
        var day_of_week = date.getDay()
        
        return servicelevel[date_string] ||
            ( (day_of_week == 0)        ? 'sunday'
            : (day_of_week == 6)        ? 'saturday'
            :                             'weekday')
    }
}

// Open the package.
Holiday();

_EOT_
}
